<template>
  <el-dialog v-model="isDialogShow" :title="title" width="500" @closed="handleDialogClosed" @open="handleDialogOpen">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name"/>
      </el-form-item>
      <el-form-item label="地图显示名称" prop="dibiao">
        <el-input v-model="form.dibiao"/>
      </el-form-item>
      <el-form-item label="经度" prop="longitude">
        <el-input v-model="form.longitude" type="number"/>
      </el-form-item>
      <el-form-item label="纬度" prop="latitude">
        <el-input v-model="form.latitude" type="number"/>
      </el-form-item>
      <el-form-item label="出餐中心" prop="mealcenterid">
        <meal-center-selector v-model="form.mealcenterid"/>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="form.address" type="textarea"/>
      </el-form-item>
      <el-form-item label="选择地址">
        <map-container @click-child="handleMapClickChild"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleConfirmClick">确定</el-button>
        <el-button @click="handleCancelClick">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script lang="ts" setup>
import {computed, ref} from "vue"
import {ElForm, ElMessage} from "element-plus";
import {isAxiosError} from "axios";
import MealCenterSelector from "@/components/selector/MealCenterSelector.vue";
import {addDeliveryPoint, getDeliveryPointById, updateDeliveryPoint} from "@/api/deliveryPoint";
import {DeliveryPointRequest} from "@/api/types/deliveryPoint";
import MapContainer from "@/components/MapContainer.vue";

const props = defineProps<{ id?: number }>()
const emit = defineEmits<{
  addSuccess: []
  success: []
  updateSuccess: []
}>()
const isDialogShow = defineModel<boolean>()

const title = computed(() => props.id === undefined ? "添加配送点" : "修改配送点")
const form = ref<DeliveryPointRequest>({})
const formRef = ref<InstanceType<typeof ElForm>>()
const rules = {
  address: [
    {
      required: true,
      message: "地址不能为空",
      trigger: "blur"
    }
  ],
  name: [
    {
      required: true,
      message: "名称不能为空",
      trigger: "blur"
    }
  ],
  latitude: [
    {
      required: true,
      message: "纬度不能为空",
      trigger: "blur"
    }
  ],
  longitude: [
    {
      required: true,
      message: "经度不能为空",
      trigger: "blur"
    }
  ],
  dibiao: [
    {
      required: true,
      message: "地图显示名称不能为空",
      trigger: "blur"
    }
  ],
  mealcenterid: [
    {
      required: true,
      message: "出餐中心不能为空",
      trigger: "change"
    },
  ]
}

async function getData() {
  if (props.id !== undefined) {
    const {result} = await getDeliveryPointById(props.id)
    if (result !== undefined) {
      form.value = result[0]
    }
  }
}

function handleCancelClick() {
  isDialogShow.value = false
}

async function handleConfirmClick() {
  formRef.value?.validate(async (isValid) => {
    if (isValid) {
      try {
        if (props.id === undefined) {
          await addDeliveryPoint(form.value)
          ElMessage.success('添加成功');
          emit("addSuccess")
        } else {
          await updateDeliveryPoint(form.value)
          ElMessage.success('修改成功');
          emit("updateSuccess")
        }
        isDialogShow.value = false;
        emit("success")
      } catch (error) {
        if (isAxiosError(error) && error.response?.data.message != undefined) {
          ElMessage.error(error.response?.data.message);
        }
      }
    } else {
      ElMessage.error('表单验证失败，请检查输入');
    }
  })
}

async function handleDialogClosed() {
  formRef.value?.resetFields()
}

async function handleDialogOpen() {
  await getData()
}

function handleMapClickChild({locationval, lng, lat}: { locationval: string, lng: string, lat: string }) {
  form.value.address = locationval
  form.value.latitude = Number(lat)
  form.value.longitude = Number(lng)
}
</script>
